<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import axios from "axios";
import http from "../../http";
import {useRoute, useRouter} from 'vue-router';

const router = useRouter();
const route = useRoute();
let xid = route.query.id;
let forms = ref({
  name: '',
  resource: [],
  pid: "",
  role: 0,
  type: ""
});

let resourcelist = ref([]);
const getresourcelist = () => {
  http.get(`app/resource/get_pid_notnull/`)
      .then(res => {
        resourcelist.value = res.data.data;
      });
};

const menuItem = ref([]);
let checkall = ref(false);
const handleCheckall = (info) => {
  if (info) {
    forms.value.resource = resourcelist.value.map((item) => item.id);
  } else {
    forms.value.resource = [];
  }
};
const handlecheckone = (xid) => {
  const index = forms.value.resource.indexOf(xid);
  console.log('Index of xid:', index, 'for xid:', xid);

  if (index > -1) {
    // 如果找到了，移除它，并指定删除一个元素
    forms.value.resource.splice(index, 1);
    console.log('Removed xid:', xid);
  } else {
    // 如果没有找到，添加它
    forms.value.resource.push(xid);
  }

  console.log('Updated resource array:', forms.value.resource);
  localStorage.setItem("role_resource", JSON.stringify(forms.value.resource));
};

// 保存数据角色
const saverole = () => {
  const roleResource = JSON.parse(localStorage.getItem("role_resource") || "[]");
  const parentList = JSON.parse(localStorage.getItem("parent_list") || "[]");

  // 检查 parent_list 中的任意一个元素是否在 role_resource 中
  const isAnyParentInRoleResource = parentList.some(item => roleResource.includes(item));

  if (isAnyParentInRoleResource) {
    ElMessage.error('parent_list 中存在已在 role_resource 中的元素，不允许修改');
    return;
  }

  http.post(`/app/role/update_role_list/`, rolelist_one.value)
      .then(res => {
        console.log(rolelist_one.value);
        console.log(res.data);
        ElMessage.success('修改成功');
        router.push("/role");
      })
      .catch(error => {
        console.error('请求失败', error);
        ElMessage.error('修改失败，请稍后再试');
      });
};



// 获取基础角色
let role_inheritlist = ref([]);
const get_role_inherit = () => {
  http.get(`app/role/get_role_inherit/`)
      .then(res => {
        console.log(res);
        role_inheritlist.value = res.data.data;
      });
};

const gorole = () => {
  router.push("/role");
};

let rolelist_one = ref([]);
// 查询当前角色继承角色以及父类资源和子类资源
const selectinherit = (info) => {
  if (info == 0) {
    forms.value.resource = [];
    forms.value.type = 0;
    rolelist_one.value.pname = "基础角色"; // 更新继承角色的名字
  } else {
    http.get(`/app/role/${info}/`)
        .then(res => {
          console.log("==============");
          console.log(res.data.resource);
          console.log(info);
          forms.value.resource = res.data.resource.map((item) => item);
          console.log(forms.value.resource);
          forms.value.type = 1;
          getrole_one(info); // 调用 getrole_one 并传递 info 作为 pid
        });
  }
};
const getrole_one = (pid) => {
  http.post(`/app/role/get_pid_xid/`, {'xid': xid, "pid": pid || route.query.pid})
      .then(res => {
        console.log(res.data);
        rolelist_one.value = res.data.data;
        localStorage.setItem("parent_list", JSON.stringify(res.data.parent_list));
        // 确保 pname 和 name 被正确设置
        if (res.data.data && res.data.data.pname) {
          rolelist_one.value.pname = res.data.data.pname;
        }
        if (res.data.data && res.data.data.name) {
          rolelist_one.value.name = res.data.data.name;
        }
      });
};


onMounted(() => {
  get_role_inherit();
  getresourcelist();
  getrole_one();
});
</script>

<template>
  <el-form :model="rolelist_one" label-width="auto" style="max-width: 600px">
    <el-form-item label="继承角色">
      <el-select v-model="rolelist_one.pname" placeholder="请选择继承的角色" style="width: 240px;">
        <el-option label="0" value="0" @click="selectinherit(0)"></el-option>
        <el-option :label="item.name" :value="item.id" v-for="(item, key) in role_inheritlist"
                   @click="selectinherit(item.id)"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="角色名称">
      <el-input v-model="rolelist_one.name" style="width: 240px;"></el-input>
    </el-form-item>
  </el-form>
  <div style="margin-top: 50px; width: 800px;">
    <h1 style="font-size: 20px;">角色权限</h1>
    <el-checkbox style="margin-top: 10px;" v-model="checkall" @change="handleCheckall">全选</el-checkbox>
    <el-checkbox-group v-model="rolelist_one.resource" style="margin-top: 10px;">
      <el-checkbox v-for="i in resourcelist" :value="i.id" @change="handlecheckone(i.id)" selected>{{
          i.name
        }}
      </el-checkbox>
    </el-checkbox-group>
  </div>
  <el-button type="primary" style="margin-top: 20px; margin-right: 20px;" @click="saverole">保存</el-button>
  <el-button style="margin-top: 20px;" @click="gorole">返回</el-button>
</template>

<style scoped>
.quan {
  width: 100%;
  height: 100vh;
}
</style>
